import OSS from 'ali-oss'
import reg from './reg'

import base64 from '@/ossutil/base64.js'
import env from '@/ossutil/config.js'

import Crypto from '@/ossutil/hmac.js'

export const ossDomain = 'https://ykjxcx.oss-cn-hangzhou.aliyuncs.com'

const OSSConfig = {
  uploadHost: 'https://aoshengxcx.oss-cn-hangzhou.aliyuncs.com/', //OSS上传地址
  ossParams: {
    region: 'oss-cn-hangzhou',
    success_action_status: '200', // 默认200
    accessKeyId: 'LTAI5tDndfytDiz2LT69Jdps',
    accessKeySecret: 's14CzxKso3HWChjP9bzwMXM3K4bO5a',
    // bucket: 'kindergarten-oss',
    bucket: 'aoshengxcx',
    timeout: 87600 //这个是上传文件时Policy的失效时间
  }
}

const getPolicyBase64 = function () {
  let date = new Date()
  date.setHours(date.getHours() + env.timeout)
  let srcT = date.toISOString()
  const policyText = {
    expiration: srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    conditions: [
      ['content-length-range', 0, 200 * 1024 * 1024] // 设置上传文件的大小限制,200mb
    ]
  }
  const policyBase64 = base64.encode(JSON.stringify(policyText))
  return policyBase64
}
const policyBase64 = getPolicyBase64()

const getSignature = function (policyBase64) {
  // console.log(policyBase64)
  const accesskey = env.AccessKeySecret
  // console.log(accesskey)
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  })

  const signature = Crypto.util.bytesToBase64(bytes)
  // console.log(signature)
  return signature
}
function random_string(len) {
  len = len || 32
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
  var maxPos = chars.length
  var pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

/**
 *
 * @param event 上传图片的资源路径
 * @param type 图片资源类型
 * @param dir oss要保存的文件夹
 * @returns {OSS文件路径}
 */

function uploadOSS(file) {
  return new Promise(async (resolve, reject) => {
    const client = new OSS({
      region: OSSConfig.ossParams.region,
      accessKeyId: OSSConfig.ossParams.accessKeyId,
      accessKeySecret: OSSConfig.ossParams.accessKeySecret,
      secure: true,
      bucket: OSSConfig.ossParams.bucket,
      signature: getSignature(policyBase64)
    })
    let fileName = reg.getFileType(file.name)

    const aliyunFileKey =
      OSSConfig.ossParams.bucket +
      '/aos/' +
      new Date().getTime() +
      Math.floor(Math.random() * 150) +
      '.' +
      fileName
    var result = await client.multipartUpload(aliyunFileKey, file)
    var url = OSSConfig.uploadHost + result.name
    // resolve(url);
  })
}

export { uploadOSS, getSignature, getPolicyBase64 }
